﻿using System.Collections.ObjectModel;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using AirCtrl.Wpf.Core;
using CommunityToolkit.Mvvm.ComponentModel;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace AirCtrl.Wpf.Views;

public partial class MainViewModel :ObservableObject
{
    [ObservableProperty] private CaptureViewModel _captureVm ;
    [ObservableProperty] private ObservableCollection<CameraViewModel> _cameraVms = new();
    [ObservableProperty] private double _cameraHeight;
    [ObservableProperty] private double _cameraWidth;

    /// <summary>
    /// 每行的相机数量
    /// </summary>
    public double RowCameraCount { get; }= 3;

    public MainViewModel()
    {
        var cameras =DevicesConfig.Instance.CameraNames;

        foreach (var item in cameras)
        {
            var cameraName = item;
            var itemVm = new CameraViewModel(){Title = cameraName};
            CameraVms.Add(itemVm);
        }
        CaptureVm = new CaptureViewModel(CameraVms);

        InitUdpSessions();
    }

    public void InitUdpSessions()
    {
        foreach (var kv in DevicesConfig.Instance.CameraUdpPorts)
        {
            var cvm = CameraVms.FirstOrDefault(a => a.Title == kv.Key);
            if (cvm == null) continue;

            var udpSession = new UdpSession();
            udpSession.Setup(new TouchSocketConfig()
                .SetBindIPHost(new IPHost($"{DevicesConfig.Instance.CameraUdpIp}:{kv.Value}"))
                .SetUdpDataHandlingAdapter(() => new UdpPackageAdapter())); //加载配置
            udpSession.Start(); 
            // 地面端数据接收
            udpSession.Received += (s, data) =>
            {
                var angle = DevicesConfig.Instance.CameraRotateAngle.ContainsKey(kv.Key)
                    ? DevicesConfig.Instance.CameraRotateAngle[kv.Key]
                    : 0;
                var imgByte = data.ByteBlock.Span.ToArray();
                cvm.ImageSource = ByteArrayToBitmapImage(imgByte, angle);
                // 地面转发第三方
                CameraUdpManager.Instance.Send(cvm.Title, imgByte);
                return EasyTask.CompletedTask;
            };
        }
    }

    public async Task GetTemperatureInfo(double x, double y)
    {
        var t = await CmdGroundClient.Instance.GetTemperature(x, y);

        var cameraTitle = "长波热像仪";
        var vm = CameraVms.FirstOrDefault(a => a.Title == cameraTitle);
        vm.Info = $"坐标：({x},{y})  温度：{t}℃";
    }


    private BitmapImage ByteArrayToBitmapImage(byte[] bytes, int angle)
    {
        if (bytes == null || bytes.Length == 0)
            return null;

        var bitmapImage = new BitmapImage();
        using (var stream = new System.IO.MemoryStream(bytes))
        {
            bitmapImage.BeginInit();
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.StreamSource = stream;
            bitmapImage.EndInit();
        }
        if (angle != 0)
        {
            var rotatedImage = new TransformedBitmap(bitmapImage, new RotateTransform(angle));

            return TransformedBitmapToBitmapImage(rotatedImage);
        }

        bitmapImage.Freeze(); // 冻结对象以提高性能（线程安全）
        return bitmapImage;
    }
    private BitmapImage TransformedBitmapToBitmapImage(TransformedBitmap transformedBitmap)
    {
        if (transformedBitmap == null)
            return null;

        var bitmapImage = new BitmapImage();
        using (var stream = new System.IO.MemoryStream())
        {
            var encoder = new PngBitmapEncoder(); // 使用 PNG 编码器
            encoder.Frames.Add(BitmapFrame.Create(transformedBitmap));
            encoder.Save(stream);

            bitmapImage.BeginInit();
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.StreamSource = new System.IO.MemoryStream(stream.ToArray());
            bitmapImage.EndInit();
        }

        bitmapImage.Freeze();
        return bitmapImage;
    }
}


